﻿using System;
using System.Linq;
using System.Net.Http;
using Consul;
using RestTemplateCore;

namespace ServiceConsumer
{
    class Program
    {
        static void Main(string[] args)
        {
            //GetConsulServices();
            RequestConsulServicesForRestTemplateCore();
            Console.ReadKey();
        }

        /// <summary>
        /// 获取Consul中的注册的服务信息
        /// </summary>
        public static void GetConsulServices()
        {
            using (var consulClient = new ConsulClient(c => c.Address = new Uri("http://127.0.0.1:8500")))
            {
                var services = consulClient.Agent.Services().Result.Response;
                foreach (var service in services.Values)
                {
                    Console.WriteLine($"id={service.ID},name={service.Service},ip={service.Address},port={service.Port}");
                }

                var servicesValue = services.Values.Where(s => s.Service.Equals("MsgService", StringComparison.OrdinalIgnoreCase));
                if (!servicesValue.Any())
                {
                    Console.WriteLine("找不到服务的实例");
                }
                else
                {
                    var service = servicesValue.ElementAt(Environment.TickCount % servicesValue.Count());
                    Console.WriteLine($"{service.Address}:{service.Port}");
                }

            }
        }

        /// <summary>
        /// 使用consul调用API
        /// </summary>
        public static void RequestConsulServicesForRestTemplateCore()
        {
            //或者使用Nuget: 地址：https://www.nuget.org/packages/RestTemplateCore

            using (HttpClient httpClient = new HttpClient())
            {
                RestTemplate rest = new RestTemplate(httpClient);
                Console.WriteLine("---查询数据---------");
                var ret1 =
                    rest.GetForEntityAsync<Product[]>("http://ProductService/api/Product/").Result;
                Console.WriteLine(ret1.StatusCode);
                if (ret1.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    foreach (var p in ret1.Body)
                    {
                        Console.WriteLine($"id={p.Id},name={p.Name}");
                    }
                }
                Console.WriteLine("---新增数据---------");
                Product newP = new Product();
                newP.Id = 888;
                newP.Name = "辛增";
                newP.Price = 88.8;
                var ret = rest.PostAsync("http://ProductService/api/Product/", newP).Result;
                Console.WriteLine(ret.StatusCode);
            }
            Console.ReadKey();
        }
    }
}
